# Create your views here.
import random

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from utils.response import APIResponse
from .models import VipCard, VipUser
from .serializer import VipcardSerializer, VipuserSerializer


class VipCardView(ModelViewSet):
    queryset = VipCard.objects.all()
    serializer_class = VipcardSerializer


class VipUserView(ModelViewSet):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated]
    queryset = VipUser.objects.all()
    serializer_class = VipuserSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['username']

    def create(self, request, *args, **kwargs):
        while True:
            ran_str = ''.join(random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], 10))
            ran_str = 'KH' + ran_str
            es = VipUser.objects.filter(cardno=ran_str)
            if len(es) == 0:
                break
            else:
                continue
        cardno = ran_str
        request.data['cardno'] = cardno
        VipUser.objects.create(**request.data)
        return APIResponse(msg='加入成功')

    def update(self, request, *args, **kwargs):
        res = VipUser.objects.filter(cardno=request.data['cardno']).first()
        VipUser.objects.filter(cardno=request.data['cardno']).update(daynum=res.daynum + request.data['daynum'])
        return APIResponse(msg="续费成功")
